<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ total }}</div>
            <div class="stat-label">总评估数量</div>
          </div>
          <i class="el-icon-s-data stat-icon"></i>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ todayCount }}</div>
            <div class="stat-label">今日评估</div>
          </div>
          <i class="el-icon-date stat-icon"></i>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ averagePrice }}</div>
            <div class="stat-label">平均估价（万元）</div>
          </div>
          <i class="el-icon-money stat-icon"></i>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ inspectionData ? '已完成' : '未检测' }}</div>
            <div class="stat-label">车况检测状态</div>
          </div>
          <i class="el-icon-setting stat-icon"></i>
        </el-card>
      </el-col>
    </el-row>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户" prop="sellerId">
        <el-select
          v-model="queryParams.sellerId"
          placeholder="请选择客户"
          clearable
          style="width: 200px"
          filterable
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.id"
            :label="(customer.nickname || '未设置昵称') + ' (' + (customer.phone || '未绑定手机') + ')'"
            :value="customer.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brandId">
        <el-select
          v-model="queryParams.brandId"
          placeholder="请选择品牌"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="brand in brandList"
            :key="brand.id"
            :label="brand.brandName"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="事故情况" prop="accidentStatus">
        <el-select
          v-model="queryParams.accidentStatus"
          placeholder="请选择事故情况"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="option in accidentStatusOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评估价格" prop="evaluationPrice">
        <el-input
          v-model="queryParams.evaluationPrice"
          placeholder="请输入评估价格"
          clearable
          style="width: 150px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评估时间" prop="evaluationTime">
        <el-date-picker clearable
          v-model="queryParams.evaluationTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择评估时间"
          style="width: 150px">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:evaluation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['car:evaluation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['car:evaluation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['car:evaluation:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-document"
          size="mini"
          @click="handleInspectionReport"
          :disabled="!inspectionData"
        >车况报告</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="evaluationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评估ID" align="center" prop="id" />
      <el-table-column label="客户信息" align="center" prop="sellerId" width="200">
        <template slot-scope="scope">
          {{ getCustomerName(scope.row.sellerId) }}
        </template>
      </el-table-column>
      <el-table-column label="关联车辆" align="center" prop="carId" width="200">
        <template slot-scope="scope">
          {{ getCarInfo(scope.row.carId) }}
        </template>
      </el-table-column>
      <el-table-column label="品牌" align="center" prop="brandId" width="120">
        <template slot-scope="scope">
          {{ getBrandName(scope.row.brandId) }}
        </template>
      </el-table-column>
      <el-table-column label="车系" align="center" prop="seriesId" width="120">
        <template slot-scope="scope">
          {{ getSeriesName(scope.row.seriesId) }}
        </template>
      </el-table-column>
      <el-table-column label="首次注册日期" align="center" prop="registerTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="行驶里程" align="center" prop="mileage" width="120">
        <template slot-scope="scope">
          {{ scope.row.mileage }}万公里
        </template>
      </el-table-column>
      <el-table-column label="事故情况" align="center" prop="accidentStatus" width="100">
        <template slot-scope="scope">
          <el-tag 
            :type="scope.row.accidentStatus === 0 ? 'success' : scope.row.accidentStatus === 1 ? 'warning' : 'danger'"
          >
            {{ getAccidentStatusLabel(scope.row.accidentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="评估价格" align="center" prop="evaluationPrice" width="120">
        <template slot-scope="scope">
          <span style="color: #E6A23C; font-weight: bold;">
            ￥{{ scope.row.evaluationPrice ? scope.row.evaluationPrice.toLocaleString() : '-' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="评估时间" align="center" prop="evaluationTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.evaluationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['car:evaluation:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['car:evaluation:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改卖车评估（卖车-评估结果页）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <!-- 测试标记：如果你看到这行文字，说明前端文件已更新 -->
      <div style="background: red; color: white; padding: 10px; margin-bottom: 20px;">
        🔴 测试标记：前端文件已更新 - 请选择客户后再填写其他信息
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择客户" prop="sellerId">
              <el-select 
                v-model="form.sellerId" 
                placeholder="请选择客户" 
                clearable 
                style="width: 100%"
                filterable
                @change="handleCustomerChange"
              >
                <el-option
                  v-for="customer in customerList"
                  :key="customer.id"
                  :label="(customer.nickname || '未设置昵称') + ' (' + (customer.phone || '未绑定手机') + ')'"
                  :value="customer.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌选择" prop="brandId">
              <el-select 
                v-model="form.brandId" 
                placeholder="请选择车辆品牌" 
                clearable 
                style="width: 100%"
                @change="handleBrandChange"
              >
                <el-option
                  v-for="brand in brandList"
                  :key="brand.id"
                  :label="brand.brandName"
                  :value="brand.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车系选择" prop="seriesId">
              <el-select 
                v-model="form.seriesId" 
                placeholder="请先选择品牌" 
                clearable 
                style="width: 100%"
                :disabled="!form.brandId"
              >
                <el-option
                  v-for="series in seriesList"
                  :key="series.id"
                  :label="series.seriesName"
                  :value="series.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联车辆" prop="carId">
              <el-select 
                v-model="form.carId" 
                placeholder="请选择关联车辆" 
                clearable 
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="car in carList"
                  :key="car.id"
                  :label="`${car.carCode} - ${car.modelName}`"
                  :value="car.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事故情况" prop="accidentStatus">
              <el-select v-model="form.accidentStatus" placeholder="请选择事故情况" clearable style="width: 100%">
                <el-option
                  v-for="option in accidentStatusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首次注册日期" prop="registerTime">
              <el-date-picker 
                clearable
                v-model="form.registerTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择首次注册日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行驶里程（万公里）" prop="mileage">
              <el-input-number 
                v-model="form.mileage" 
                placeholder="请输入行驶里程" 
                :min="0"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评估价格（元）" prop="evaluationPrice">
              <el-input-number 
                v-model="form.evaluationPrice" 
                placeholder="请输入评估价格" 
                :min="0"
                :precision="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="评估时间" prop="evaluationTime">
              <el-date-picker 
                clearable
                v-model="form.evaluationTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择评估时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列，保持布局 -->
          </el-col>
        </el-row>
        
        <!-- 智能估价按钮 -->
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button 
                type="warning" 
                icon="el-icon-magic-stick" 
                @click="calculateEstimatedPrice"
                :disabled="!form.brandId || !form.seriesId || !form.registerTime || !form.mileage"
              >
                智能价格估算
              </el-button>
              <el-button 
                type="success" 
                icon="el-icon-search" 
                @click="showInspection = !showInspection"
                style="margin-left: 10px;"
              >
                {{ showInspection ? '隐藏' : '显示' }}车况检测
              </el-button>
              <span style="margin-left: 10px; color: #999; font-size: 12px;">
                需要选择品牌、车系、注册日期和里程后才能估价
              </span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 车况检测组件 -->
        <div v-if="showInspection">
          <el-divider content-position="center">车况检测评估</el-divider>
          <CarInspection @inspection-completed="handleInspectionCompleted" />
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEvaluation, getEvaluation, delEvaluation, addEvaluation, updateEvaluation } from "@/api/car/evaluation"
import { listBrand } from "@/api/car/brand"
import { listSeries } from "@/api/car/series"
import { listInfo } from "@/api/car/info"
import { listCustomer } from "@/api/car/customer"
import { getDictData, getDictLabel } from "@/utils/dictUtils"
import CarInspection from "@/components/CarInspection"

export default {
  name: "Evaluation",
  components: {
    CarInspection
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卖车评估（卖车-评估结果页）表格数据
      evaluationList: [],
      // 品牌列表
      brandList: [],
      // 车系列表
      seriesList: [],
      // 车辆列表
      carList: [],
      // 客户列表
      customerList: [],
      // 事故情况字典
      accidentStatusOptions: [],
      // 是否显示车况检测
      showInspection: false,
      // 检测结果
      inspectionData: null,
      // 统计数据
      todayCount: 0,
      averagePrice: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sellerId: null,
        carId: null,
        brandId: null,
        seriesId: null,
        registerTime: null,
        mileage: null,
        accidentStatus: null,
        evaluationPrice: null,
        evaluationTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sellerId: [
          { required: true, message: "卖家ID不能为空", trigger: "change" }
        ],
        brandId: [
          { required: true, message: "品牌ID不能为空", trigger: "change" }
        ],
        seriesId: [
          { required: true, message: "车系ID不能为空", trigger: "change" }
        ],
        registerTime: [
          { required: true, message: "首次注册日期不能为空", trigger: "blur" }
        ],
        mileage: [
          { required: true, message: "行驶里程不能为空", trigger: "blur" }
        ],
        accidentStatus: [
          { required: true, message: "事故情况不能为空", trigger: "change" }
        ],
        evaluationPrice: [
          { required: true, message: "评估价格不能为空", trigger: "blur" }
        ],
        evaluationTime: [
          { required: true, message: "评估时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.loadBasicData()
  },
  methods: {
    /** 查询卖车评估（卖车-评估结果页）列表 */
    getList() {
      this.loading = true
      listEvaluation(this.queryParams).then(response => {
        this.evaluationList = response.rows
        this.total = response.total
        this.loading = false
        // 计算统计数据
        this.calculateStatistics()
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sellerId: null,
        carId: null,
        brandId: null,
        seriesId: null,
        registerTime: null,
        mileage: null,
        accidentStatus: null,
        evaluationPrice: null,
        evaluationTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加卖车评估（卖车-评估结果页）"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getEvaluation(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改卖车评估（卖车-评估结果页）"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEvaluation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addEvaluation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除卖车评估（卖车-评估结果页）编号为"' + ids + '"的数据项？').then(function() {
        return delEvaluation(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/evaluation/export', {
        ...this.queryParams
      }, `evaluation_${new Date().getTime()}.xlsx`)
    },
    /** 加载基础数据 */
    async loadBasicData() {
      try {
        // 加载品牌数据
        const brandResponse = await listBrand({ pageNum: 1, pageSize: 1000 })
        this.brandList = brandResponse.rows || []
        
        // 加载车辆数据
        const carResponse = await listInfo({ pageNum: 1, pageSize: 1000 })
        this.carList = carResponse.rows || []
        
        // 加载客户数据
        const customerResponse = await listCustomer({ pageNum: 1, pageSize: 1000 })
        this.customerList = customerResponse.rows || []
        
        // 加载事故情况字典
        this.accidentStatusOptions = [
          { label: '无事故', value: 0 },
          { label: '轻微事故', value: 1 },
          { label: '重大事故', value: 2 }
        ]
      } catch (error) {
        console.error('加载基础数据失败:', error)
      }
    },
    /** 客户选择变化 */
    handleCustomerChange(customerId) {
      if (customerId) {
        const customer = this.customerList.find(item => item.id === customerId)
        if (customer) {
          this.$message.success('已选择客户：' + (customer.nickname || '未设置昵称'))
        }
      }
    },
    /** 品牌变化时加载车系 */
    async handleBrandChange(brandId) {
      if (brandId) {
        try {
          const response = await listSeries({ brandId, pageNum: 1, pageSize: 1000 })
          this.seriesList = response.rows || []
        } catch (error) {
          console.error('加载车系数据失败:', error)
          this.seriesList = []
        }
      } else {
        this.seriesList = []
      }
      // 清空车系选择
      this.form.seriesId = null
    },
    /** 获取客户名称 */
    getCustomerName(customerId) {
      const customer = this.customerList.find(item => item.id === customerId)
      return customer ? (customer.nickname || '未设置昵称') + ' (' + (customer.phone || '未绑定手机') + ')' : customerId
    },
    /** 获取品牌名称 */
    getBrandName(brandId) {
      const brand = this.brandList.find(item => item.id === brandId)
      return brand ? brand.brandName : brandId
    },
    /** 获取车系名称 */
    getSeriesName(seriesId) {
      const series = this.seriesList.find(item => item.id === seriesId)
      return series ? series.seriesName : seriesId
    },
    /** 获取车辆信息 */
    getCarInfo(carId) {
      if (!carId || !this.carList || this.carList.length === 0) {
        return carId || '-'
      }
      const car = this.carList.find(item => item.id === carId)
      return car ? `${car.carCode} - ${car.modelName}` : carId
    },
    /** 获取事故状态标签 */
    getAccidentStatusLabel(status) {
      const option = this.accidentStatusOptions.find(item => item.value === status)
      return option ? option.label : status
    },
    /** 智能价格估算 */
    calculateEstimatedPrice() {
      if (!this.form.brandId || !this.form.seriesId || !this.form.registerTime || !this.form.mileage) {
        return
      }
      
      // 简单的价格估算算法（实际项目中应该调用专业的评估接口）
      const currentYear = new Date().getFullYear()
      const registerYear = new Date(this.form.registerTime).getFullYear()
      const carAge = currentYear - registerYear
      const mileage = parseFloat(this.form.mileage)
      
      // 基础价格（可以根据品牌车系从数据库获取）
      let basePrice = 100000 // 10万基础价格
      
      // 年限折旧：每年折旧10%
      let depreciation = Math.pow(0.9, carAge)
      
      // 里程折旧：每万公里折旧2%
      let mileageDepreciation = Math.pow(0.98, mileage)
      
      // 事故折旧
      let accidentDepreciation = 1
      if (this.form.accidentStatus === 1) {
        accidentDepreciation = 0.85 // 轻微事故85%
      } else if (this.form.accidentStatus === 2) {
        accidentDepreciation = 0.7 // 重大事故70%
      }
      
      const estimatedPrice = Math.round(basePrice * depreciation * mileageDepreciation * accidentDepreciation)
      this.form.evaluationPrice = estimatedPrice
      
      this.$message.success(`智能估价完成：${estimatedPrice.toLocaleString()} 元`)
    },
    /** 处理车况检测完成 */
    handleInspectionCompleted(inspectionResult) {
      this.inspectionData = inspectionResult
      
      // 根据检测结果调整评估价格
      if (this.form.evaluationPrice && inspectionResult.adjustmentFactor) {
        const adjustedPrice = Math.round(this.form.evaluationPrice * inspectionResult.adjustmentFactor)
        
        this.$confirm(
          `根据车况检测结果（${inspectionResult.grade}），建议将评估价格调整为 ${adjustedPrice.toLocaleString()} 元，是否应用此价格？`,
          '价格调整建议',
          {
            confirmButtonText: '应用',
            cancelButtonText: '取消',
            type: 'info'
          }
        ).then(() => {
          this.form.evaluationPrice = adjustedPrice
          this.$message.success('价格已根据车况检测结果调整')
        }).catch(() => {
          this.$message.info('已取消价格调整')
        })
      } else {
        this.$message.success('车况检测完成，请先进行智能估价后再应用检测结果')
      }
    },
    /** 导出车况检测报告 */
    handleInspectionReport() {
      if (!this.inspectionData) {
        this.$message.warning('请先完成车况检测')
        return
      }
      
      // 生成报告内容
      const reportContent = `车况检测报告
================

检测时间：${new Date().toLocaleString()}
综合评分：${this.inspectionData.score}分
车况等级：${this.inspectionData.grade}

详细评分：
- 车身外观：${this.inspectionData.details.bodyCondition}星
- 漆面状况：${this.inspectionData.details.paintCondition}星
- 轮胎磨损：${this.inspectionData.details.tireCondition}星
- 发动机状况：${this.inspectionData.details.engineCondition}星
- 变速箱状况：${this.inspectionData.details.gearboxCondition}星
- 底盘状况：${this.inspectionData.details.chassisCondition}星
- 座椅状况：${this.inspectionData.details.seatCondition}星
- 仪表功能：${this.inspectionData.details.dashboardCondition}星
- 空调系统：${this.inspectionData.details.acCondition}星
- 音响导航：${this.inspectionData.details.audioCondition}星

检测备注：
${this.inspectionData.details.remarks || '无'}

生成时间：${new Date().toLocaleString()}`
      
      // 创建下载链接
      const blob = new Blob([reportContent], { type: 'text/plain;charset=utf-8' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `车况检测报告_${new Date().getTime()}.txt`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      
      this.$message.success('车况检测报告已导出')
    },
    /** 计算统计数据 */
    calculateStatistics() {
      const today = new Date().toISOString().split('T')[0]
      
      // 计算今日评估数量
      this.todayCount = this.evaluationList.filter(item => {
        const evaluationDate = item.evaluationTime ? item.evaluationTime.split(' ')[0] : ''
        return evaluationDate === today
      }).length
      
      // 计算平均估价
      const validPrices = this.evaluationList
        .filter(item => item.evaluationPrice && item.evaluationPrice > 0)
        .map(item => parseFloat(item.evaluationPrice))
      
      if (validPrices.length > 0) {
        const averageValue = validPrices.reduce((sum, price) => sum + price, 0) / validPrices.length
        this.averagePrice = (averageValue / 10000).toFixed(1) // 转换为万元
      } else {
        this.averagePrice = 0
      }
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 统计卡片样式 */
.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px 0 rgba(0, 0, 0, 0.15);
}

.stat-card:nth-child(1) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-card:nth-child(2) {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.stat-card:nth-child(3) {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.stat-card:nth-child(4) {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-content {
  position: relative;
  z-index: 2;
  padding: 20px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 32px;
  opacity: 0.3;
  z-index: 1;
}

.el-form-item {
  margin-bottom: 18px;
}

.dialog-footer {
  text-align: center;
  padding-top: 20px;
}

/* 评估价格高亮样式 */
.price-highlight {
  color: #E6A23C;
  font-weight: bold;
  font-size: 16px;
}

/* 事故状态标签样式 */
.el-tag {
  margin: 0;
}

/* 表格行高 */
::v-deep .el-table .el-table__row {
  height: 50px;
}

/* 智能估价按钮样式 */
.el-button--warning {
  background: linear-gradient(135deg, #FFA726, #FF7043);
  border: none;
  color: white;
  font-weight: bold;
}

.el-button--warning:hover {
  background: linear-gradient(135deg, #FF9800, #FF5722);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(255, 152, 0, 0.3);
}

/* 输入框样式优化 */
.el-input__inner {
  border-radius: 6px;
}

.el-select .el-input__inner {
  border-radius: 6px;
}

/* 对话框样式优化 */
::v-deep .el-dialog__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px 8px 0 0;
}

::v-deep .el-dialog__title {
  color: white;
  font-weight: bold;
}

::v-deep .el-dialog__body {
  padding: 30px 20px;
}
</style>
